package com.lizhi.dingdong.apk.service

import android.Manifest
import android.R
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import com.google.gson.Gson
import com.lizhi.dingdong.apk.MainActivity
import com.lizhi.dingdong.apk.data.NotificationItem
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.Response
import okhttp3.WebSocket


class WebSocketService : Service() {

    private val CHANNEL_ID = "web_socket_service"
    private val CHANNEL_NAME = "web_socket_service"

    private val Foreground_CHANNEL_ID = "web_socket_service_running"
    private val Foreground_CHANNEL_NAME = "web_socket_service_running"

    private val NOTIFICATION_ID = 8443 // 前台服务通知 ID (用于 keep service alive)

    private val serviceJob = SupervisorJob()
    private val serviceScope = CoroutineScope(Dispatchers.IO + serviceJob)

    private val _notificationFlow = MutableStateFlow<NotificationItem>(buildNotificationItem())
    // 暴露为只读的 StateFlow
    val notificationFlow: StateFlow<NotificationItem> = _notificationFlow.asStateFlow()

    private var webSocketConnector: WebSocketConnector? = null

    private var isConnected: Boolean = false

    // 💥 关键修改: 用于给后台新消息通知生成唯一 ID 💥
    private var uniqueNotificationIdCounter = 9500

    private val connectServerFailId = 9549

    companion object {
        var INSTANCE: WebSocketService? = null

        val currentDataFlow: StateFlow<NotificationItem>?
            get() = INSTANCE?.notificationFlow

        @Volatile
        var isAppInForeground: Boolean = false
    }

    override fun onCreate() {
        super.onCreate()
        Log.i("WebSocketService", "WebSocketService onCreate")

        INSTANCE = this // 设置实例引用

        // 确保通道已创建，以便后续的两个通知都能使用
        ensureNotificationChannelCreated()
        createForegroundNotificationChannel()

        // 💥 关键修正 1: 启动前台服务 💥
        startForeground(NOTIFICATION_ID, createForegroundNotification())

        if (webSocketConnector == null){
            // WebSocketConnector 初始化
            webSocketConnector = WebSocketConnector(CustomWebSocketListener())
            webSocketConnector?.initWebSocket()
        }
    }

    override fun onStartCommand(
        intent: Intent?,
        flags: Int,
        startId: Int
    ): Int {
        Log.i("WebSocketService", "WebSocketService onStartCommand")

        // 连接websocket server
        if (isConnected == false){
            webSocketConnector?.connectServer()
        }
        return START_STICKY //服务被杀死后尝试重启
    }

    override fun onDestroy() {
        super.onDestroy()
        //webSocketClient!!.close(1000, "Service Destroyed")
        webSocketConnector?.close()
        serviceJob.cancel()
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    // 确保通知通道已创建
    private fun ensureNotificationChannelCreated() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                CHANNEL_NAME,
                // 前台服务通道的优先级通常设置为 LOW 或 DEFAULT，以免过多干扰用户
                NotificationManager.IMPORTANCE_HIGH
            ).apply {
                setShowBadge(true)
            }

            val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            manager.createNotificationChannel(channel)
        }
    }

    private fun createForegroundNotificationChannel(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                Foreground_CHANNEL_ID,
                Foreground_CHANNEL_ID,
                // 前台服务通道的优先级通常设置为 LOW 或 DEFAULT，以免过多干扰用户
                NotificationManager.IMPORTANCE_HIGH
            ).apply {
                setShowBadge(false)
            }

            val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            manager.createNotificationChannel(channel)
        }
    }

    private fun createForegroundNotification(): Notification {

        // 创建 PendingIntent，点击通知后返回 MainActivity
        val intent = Intent(this, MainActivity::class.java).apply {
            // 确保 Activity 启动的 flags 正确
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        val pendingIntent: PendingIntent = PendingIntent.getActivity(
            this,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        return NotificationCompat.Builder(this, Foreground_CHANNEL_ID)
            .setContentTitle("叮咚正在运行")
            .setContentText("叮咚后台运行")
            .setSmallIcon(R.drawable.ic_dialog_info)
            .setPriority(NotificationCompat.PRIORITY_LOW) // 低优先级
            .setDefaults(Notification.DEFAULT_ALL) // 使用默认声音和震动
            .setContentIntent(pendingIntent) // 点击通知后打开应用
            .setAutoCancel(true) // 用户点击后自动消除通知
            .build()
    }

    fun messageProcess(msg: String){
        Log.d("WebSocketService", "Received message: $msg")
        // 假设服务器返回的是 JSON 字符串
        try {
            // **重要：这里需要一个解析逻辑来将 JSON 映射到 NotificationItem**
            // ⚠️ 假设您已在依赖中添加了 Gson 库
            val item = Gson().fromJson(msg, NotificationItem::class.java)
            serviceScope.launch {
                _notificationFlow.value = item
                if (!isAppInForeground) {
                    showNewDataNotification(item)
                }
            }
        } catch (e: Exception) {
            Log.e("WebSocketService", "Error parsing message", e)
        }
    }

    fun connectServerFailuer(webSocket: WebSocket,
                             t: Throwable,
                             response: Response?){
        Log.e("CustomWebSocketListener", "WebSocket connection failed: ${t.message}", t)
        showConnectServerFailNotification(t.message)
        // 连接失败后尝试重连 (实际应用中需要更复杂的指数退避逻辑)
        serviceScope.launch {
            delay(5000) // 延迟 5 秒后尝试重连
            this@WebSocketService.webSocketConnector?.connectServer()
        }
        // 连接失败，发送通知
        // TODO
    }

    /**
     * 检查应用是否具有发送通知的权限。
     */
    private fun isNotificationPermissionGranted(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // API 33 (Tiramisu) 及更高版本需要检查运行时权限 POST_NOTIFICATIONS
            ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.POST_NOTIFICATIONS
            ) == PackageManager.PERMISSION_GRANTED
        } else {
            // API 32 (S) 及更低版本，只需检查是否禁用了应用通知
            NotificationManagerCompat.from(this).areNotificationsEnabled()
        }
    }

    // 💥 新增核心方法：用于发送新消息提醒（高优先级）
    private fun showNewDataNotification(content: NotificationItem) {

        // 💥 新增权限检查 💥
        if (!isNotificationPermissionGranted()) {
            Log.w("WebSocketService", "Notification permission not granted. Cannot show new data notification.")
            // 可以在这里返回或者记录日志，通常你应该在 Activity 中处理权限请求。
            return
        }

        // 创建 PendingIntent，点击通知后返回 MainActivity
        val intent = Intent(this, MainActivity::class.java).apply {
            // 确保 Activity 启动的 flags 正确
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        val pendingIntent: PendingIntent = PendingIntent.getActivity(
            this,
            uniqueNotificationIdCounter,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        // 构建新消息通知
        val notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle(content.title)
            .setContentText(content.content)
            .setTicker("您收到了一条实时通知") // 在状态栏短暂显示文本
            .setSmallIcon(R.drawable.ic_dialog_info)
            .setPriority(NotificationCompat.PRIORITY_HIGH) // 💥 高优先级，确保提醒效果 💥
            .setDefaults(Notification.DEFAULT_ALL) // 使用默认声音和震动
            .setContentIntent(pendingIntent) // 点击通知后打开应用
            .setAutoCancel(true) // 用户点击后自动消除通知
            .build()

        // 使用 NotificationManager 发布通知
        val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        // 关键：使用不同的 ID，保证这个新消息通知与前台服务通知是独立的
        manager.notify(uniqueNotificationIdCounter++, notification)
    }

    private fun showConnectServerFailNotification(content: String?){
        // 创建 PendingIntent，点击通知后返回 MainActivity
        val intent = Intent(this, MainActivity::class.java).apply {
            // 确保 Activity 启动的 flags 正确
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        val pendingIntent: PendingIntent = PendingIntent.getActivity(
            this,
            uniqueNotificationIdCounter,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        // 构建新消息通知
        val notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("连接websocket服务器失败")
            .setContentText(content)
            .setTicker("您收到了一条实时通知") // 在状态栏短暂显示文本
            .setSmallIcon(R.drawable.ic_dialog_alert)
            .setPriority(NotificationCompat.PRIORITY_HIGH) // 💥 高优先级，确保提醒效果 💥
            .setDefaults(Notification.DEFAULT_ALL) // 使用默认声音和震动
            .setContentIntent(pendingIntent) // 点击通知后打开应用
            .setAutoCancel(true) // 用户点击后自动消除通知
            .build()

        // 使用 NotificationManager 发布通知
        val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        // 关键：使用不同的 ID，保证这个新消息通知与前台服务通知是独立的
        manager.notify(connectServerFailId, notification)
    }

    inner class CustomWebSocketListener : WebSocketConnector.SimpleWebSocketListener() {

        override fun onOpen(webSocket: WebSocket, response: Response) {
            Log.i("WebSocketConnector", "Connection Opened: WSS")
            webSocket.send("SUBSCRIBE_TO_NOTIFICATIONS")
            this@WebSocketService.isConnected = true
        }

        override fun onMessage(webSocket: WebSocket, text: String) {
            this@WebSocketService.messageProcess(text)
        }

        override fun onFailure(
            webSocket: WebSocket,
            t: Throwable,
            response: Response?
        ) {
            this@WebSocketService.isConnected = false
            this@WebSocketService.connectServerFailuer(webSocket, t, response)
        }

        override fun onClosed(
            webSocket: WebSocket,
            code: Int,
            reason: String
        ) {
            this@WebSocketService.isConnected = false
        }
    }
}

fun buildNotificationItem(): NotificationItem{
    return NotificationItem(
        3,
        "启动初始化",
        "00:00:00",
        "启动初始化",
        "启动初始化",
        Color.Companion.Green.toArgb(),
        msgType = 0,
    )
}